import { login, getUserInfo } from '@/api/module/user'
import { setToken, getToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  username: '',
  name: '',
  avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  introduction: '',
  roles: []
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}
const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise(resolve => {
      login({ username: username.trim(), password }).then(res => {
        const { code, data } = res
        if (code === 20000) {
          commit('SET_TOKEN', data.token)
          setToken(data.token)
        }
        resolve(res)
      })
    })
  },
  signOut({ dispatch, commit }) {
    removeToken()
    dispatch('delAllViews', null, { root: true })
    commit('SET_TOKEN', '')
    commit('SET_NAME', '')
    commit('SET_USERNAME', '')
    commit('SET_AVATAR', '')
    commit('SET_INTRODUCTION', '')
    commit('SET_ROLES', [])
  },
  getUserInfo({ commit }, token) {
    return new Promise(resolve => {
      getUserInfo(token).then(res => {
        const { code, data } = res
        if (code === 20000) {
          const { avatar, introduction, username, name, roles } = data
          commit('SET_NAME', name)
          commit('SET_USERNAME', username)
          commit('SET_AVATAR', avatar)
          commit('SET_INTRODUCTION', introduction)
          commit('SET_ROLES', roles)
        }
        resolve(res)
      })
    })
  }
}

export default {
  namespace: true,
  state,
  mutations,
  actions
}
